package com.tul.exercise.base.thread.synchronize;

import com.tul.cusa.common.log.LogTracerFactory;
import com.tul.cusa.common.log.intf.ILogTracer;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 场景:某个国际化基础语言管理平台收到一个多语言翻译请求后,
 * 根据目标语种拆分为多个子线程,对翻译引擎发起翻译请求,
 * 翻译完成后,同步返回给调用方,结果由于countDown()抛出异常发生错误
 * @author tuliang
 */
public class CountDownLatchTest {
    /**
     * 日志
     */
    private static final ILogTracer TRACER = LogTracerFactory.getTracer(CountDownLatchTest.class);

    public static void main(String[] args) {
        CountDownLatch count = new CountDownLatch(3);

        Thread thread1 = new TranslateThread("1st content", count);
        Thread thread2 = new TranslateThread("2nd content", count);

        Thread thread3 = new TranslateThread("3rd content", count);
        thread1.start();
        thread2.start();
        thread3.start();

        try {
            count.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            TRACER.error("异常", e);
        }

        TRACER.info("所有线程执行完成");
    }

    /**
     * 翻译任务线程，模拟抛出异常情况
     */
    private static class TranslateThread extends Thread{
        private String content;
        private final CountDownLatch count;

        public TranslateThread(String content, CountDownLatch countDownLatch) {
            this.content = content;
            this.count = countDownLatch;
        }

        @Override
        public void run() {

            // 某种情况下，执行翻译时发生异常
            if (Math.random() > 0.5) {
                throw new RuntimeException("原文存在非法字符");
            }

            TRACER.info(content + "的翻译已经完成，译文是...");
            count.countDown();
        }
    }

}


